package cn.easyshipping.cloud.common.exception;

import cn.easyshipping.cloud.business.dto.ResponseResult;
import cn.easyshipping.cloud.common.constant.ErrorCode;
import cn.easyshipping.cloud.common.util.ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.annotation.Resource;
import java.util.List;

/**
 * 层全局异常统一处理类
 */
@RestControllerAdvice
public class RestExceptionHandler {

    private Logger log = LoggerFactory.getLogger(RestExceptionHandler.class.getName());

    @Resource
    private ResponseUtil responseUtil;
    /**
     * 处理全局异常
     */
    @ExceptionHandler(Throwable.class)
    public ResponseResult<String> handleException(Throwable e) {
        log.error("Exception,exception:{}", e);
        return responseUtil.failedResult(ErrorCode.serverError);
    }
    /**
     * 处理业务异常
     */
    @ExceptionHandler(value = BusinessException.class)
    public ResponseResult<String> businessExceptionHandler(BusinessException e) {
        log.error("BusinessException,exception:", e);
        return responseUtil.failedResult(ErrorCode.businessErrorCode);
    }

    /**
     * 处理validation 框架异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseResult<String> methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        log.error("methodArgumentNotValidExceptionHandler bindingResult.allErrors():{},exception:{}", e.getBindingResult().getAllErrors(), e);
        List<ObjectError> errors = e.getBindingResult().getAllErrors();
        return createValidExceptionResp(errors);
    }

    private ResponseResult<String> createValidExceptionResp(List<ObjectError> errors) {
        String[] msgs = new String[errors.size()];
        int i = 0;
        for (ObjectError error : errors) {
            msgs[i] = error.getDefaultMessage();
            log.info("msg={}", msgs[i]);
            i++;
        }
        return responseUtil.failedResult(ErrorCode.paramError, msgs[0]);
    }
}
